from django.db import models
from django.contrib.auth.models import AbstractUser
from history_qa.models import ProjectInfo
from knowledge1.models import Project
from django.contrib.auth.models import Permission


class UserProfile(AbstractUser):
    # app_authority = models.ManyToManyField('KnowledgeApps', blank=True, null=True)
    # project_authority = models.ManyToManyField('KnowledgeApps', blank=True, null=True)
    historyqa_permission = models.ManyToManyField('history_qa.ProjectInfo', blank=True, null=True, verbose_name='历史对话记录权限')
    knowledge_permission = models.ManyToManyField('knowledge1.Project', blank=True, null=True, verbose_name='知识库权限')
    class Meta:
        verbose_name = '用户资料'
        verbose_name_plural = '用户资料'

    def __str__(self):
        return self.username
    
    def save(self, *args, **kwargs):
        #do some custom processing here: Example: convert Image resolution to a normalized value
        super(UserProfile, self).save()
        if UserProfile.objects.get(username=self.username).historyqa_permission.all():
            if not self.has_perm('view_historyqa'):
                vi = Permission.objects.filter(codename='view_historyqa')[0]
                self.user_permissions.add(vi)
        if UserProfile.objects.get(username=self.username).knowledge_permission.all():
            if not self.has_perm('view_detail'):
                vi = Permission.objects.filter(codename='view_detail')[0]
                self.user_permissions.add(vi)
    
    
# authority